package com.jstyle.jclifexd.utils;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.google.android.gms.maps.model.LatLng;
import com.google.gson.Gson;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.ActivitiesActivity;
import com.jstyle.jclifexd.activity.MainActivity;
import com.jstyle.jclifexd.activity.NotificationlistActivity;
import com.jstyle.jclifexd.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclifexd.model.BindDeviceInfo;
import com.jstyle.jclifexd.model.NotificationData;
import com.jstyle.jclifexd.model.PathRecord;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.lang.reflect.Type;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Utils {
    // 两次点击按钮之间的点击间隔不能少于600毫秒
    private static final int MIN_CLICK_DELAY_TIME = 600;
    private static final int MIN_CLICK_DELAY_TIMEer = 1000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public static boolean isFastClicktwo() {
        boolean flag = true;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIMEer) {
            flag = false;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public static boolean checkNetWork(Context context) {
        boolean flag = false;
        ConnectivityManager cwjManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cwjManager.getActiveNetworkInfo() != null)
            flag = cwjManager.getActiveNetworkInfo().isAvailable();
        return flag;
    }


    public static final boolean isOPen(final Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }


    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }


    public static boolean isZh(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

    public static String doubleTransform(double num) {
        String strNum = num + "";
        int a = strNum.indexOf(".");
        if (a > 0) {
            //获取小数点后面的数字
            String dianAfter = strNum.substring(a + 1);
            if ("0".equals(dianAfter)) {
                return strNum + "0";
            } else {
                if (dianAfter.length() == 1) {
                    return strNum + "0";
                } else {
                    return strNum;
                }
            }
        } else {
            return strNum + ".00";
        }
    }


    public static float getGoogleDistance(LatLng start, LatLng end) {
        double lat1 = (Math.PI / 180) * start.latitude;
        double lat2 = (Math.PI / 180) * end.latitude;
        double lon1 = (Math.PI / 180) * start.longitude;
        double lon2 = (Math.PI / 180) * end.longitude;
        double R = 6371;//地球半径
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2)
                * Math.cos(lon2 - lon1))
                * R;
        return (float) d * 1000;
    }

    public static ProgressDialog progressDialog;

    public static void showProgressDialog(Activity activity, String message) {
        if (null == activity) {
            return;
        }
        if (activity.isDestroyed()) return;
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(activity, R.style.appalertdialog);
        }
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        progressDialog.setMessage(message);
        if (!activity.isFinishing()) {
            try {
                progressDialog.show();
            } catch (Exception E) {
                E.printStackTrace();
            }
        }
    }


    public static void disMissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    //判断是否在台湾
    public static boolean isTAiwan(com.amap.api.maps.model.LatLng var1) {
        List<com.amap.api.maps.model.LatLng> var0 = new ArrayList<>();
        var0.add(new com.amap.api.maps.model.LatLng(22.210757, 113.546513));
        var0.add(new com.amap.api.maps.model.LatLng(22.220009, 113.556376));
        var0.add(new com.amap.api.maps.model.LatLng(22.219557, 113.560131));
        var0.add(new com.amap.api.maps.model.LatLng(22.219724, 113.562808));
        var0.add(new com.amap.api.maps.model.LatLng(22.219724, 113.562808));
        var0.add(new com.amap.api.maps.model.LatLng(22.216864, 113.56712));
        var0.add(new com.amap.api.maps.model.LatLng(22.167888, 113.607436));
        var0.add(new com.amap.api.maps.model.LatLng(22.137694, 113.613472));
        var0.add(new com.amap.api.maps.model.LatLng(22.137694, 113.613472));
        var0.add(new com.amap.api.maps.model.LatLng(22.11486, 113.587457));
        var0.add(new com.amap.api.maps.model.LatLng(22.11178, 113.567695));
        var0.add(new com.amap.api.maps.model.LatLng(22.114726, 113.560077));
        var0.add(new com.amap.api.maps.model.LatLng(22.141243, 113.561371));
        var0.add(new com.amap.api.maps.model.LatLng(22.141243, 113.561371));
        var0.add(new com.amap.api.maps.model.LatLng(22.153026, 113.558999));
        var0.add(new com.amap.api.maps.model.LatLng(22.162064, 113.55016));
        var0.add(new com.amap.api.maps.model.LatLng(22.162064, 113.55016));
        var0.add(new com.amap.api.maps.model.LatLng(22.185693, 113.537943));
        var0.add(new com.amap.api.maps.model.LatLng(22.209252, 113.548076));
        if (var0 != null && var0.size() != 0 && var1 != null) {
            int var2;
            for (var2 = 0; var2 < var0.size(); ++var2) {
                if (var1.longitude == ((com.amap.api.maps.model.LatLng) var0.get(var2)).longitude && var1.latitude == ((com.amap.api.maps.model.LatLng) var0.get(var2)).latitude) {
                    return true;
                }
            }
            var2 = 0;
            boolean var3 = false;
            com.amap.api.maps.model.LatLng var4 = null;
            com.amap.api.maps.model.LatLng var5 = null;
            double var6 = 0.0D;
            int var8 = var0.size();
            for (int var9 = 0; var9 < var8; ++var9) {
                var4 = (com.amap.api.maps.model.LatLng) var0.get(var9);
                var5 = (com.amap.api.maps.model.LatLng) var0.get((var9 + 1) % var8);
                if (var4.latitude != var5.latitude && var1.latitude >= Math.min(var4.latitude, var5.latitude) && var1.latitude <= Math.max(var4.latitude, var5.latitude)) {
                    var6 = (var1.latitude - var4.latitude) * (var5.longitude - var4.longitude) / (var5.latitude - var4.latitude) + var4.longitude;
                    if (var6 == var1.longitude) {
                        return true;
                    }
                    if (var6 < var1.longitude) {
                        ++var2;
                    }
                }
            }
            return var2 % 2 == 1;
        } else {
            return false;
        }
    }

    /**
     * 是否在香港
     *
     * @param var1
     * @return
     */
    public static boolean isXianggan(com.amap.api.maps.model.LatLng var1) {
        List<com.amap.api.maps.model.LatLng> var0 = new ArrayList<>();
        var0.add(new com.amap.api.maps.model.LatLng(22.445883, 113.929154));
        var0.add(new com.amap.api.maps.model.LatLng(22.470079, 113.964213));
        var0.add(new com.amap.api.maps.model.LatLng(22.485787, 113.981478));
        var0.add(new com.amap.api.maps.model.LatLng(22.502390, 114.018740));
        var0.add(new com.amap.api.maps.model.LatLng(22.504206, 114.033034));
        var0.add(new com.amap.api.maps.model.LatLng(22.501687, 114.049640));
        var0.add(new com.amap.api.maps.model.LatLng(22.501153, 114.055955));
        var0.add(new com.amap.api.maps.model.LatLng(22.504341, 114.059980));
        var0.add(new com.amap.api.maps.model.LatLng(22.512334, 114.062863));
        var0.add(new com.amap.api.maps.model.LatLng(22.514971, 114.066319));
        var0.add(new com.amap.api.maps.model.LatLng(22.514369, 114.071502));
        var0.add(new com.amap.api.maps.model.LatLng(22.505164, 114.078990));
        var0.add(new com.amap.api.maps.model.LatLng(22.501926, 114.080718));
        var0.add(new com.amap.api.maps.model.LatLng(22.502735, 114.095725));
        var0.add(new com.amap.api.maps.model.LatLng(22.502586, 114.114177));
        var0.add(new com.amap.api.maps.model.LatLng(22.496206, 114.122229));
        var0.add(new com.amap.api.maps.model.LatLng(22.492133, 114.137170));
        var0.add(new com.amap.api.maps.model.LatLng(22.488512, 114.143485));
        var0.add(new com.amap.api.maps.model.LatLng(22.484873, 114.148651));
        var0.add(new com.amap.api.maps.model.LatLng(22.482833, 114.153820));
        var0.add(new com.amap.api.maps.model.LatLng(22.474272, 114.153244));
        var0.add(new com.amap.api.maps.model.LatLng(22.464612, 114.150949));
        var0.add(new com.amap.api.maps.model.LatLng(22.450247, 114.154407));
        var0.add(new com.amap.api.maps.model.LatLng(22.441265, 114.160740));
        var0.add(new com.amap.api.maps.model.LatLng(22.442974, 114.171675));
        var0.add(new com.amap.api.maps.model.LatLng(22.445657, 114.178590));
        var0.add(new com.amap.api.maps.model.LatLng(22.436448, 114.194191));
        var0.add(new com.amap.api.maps.model.LatLng(22.426537, 114.212700));
        var0.add(new com.amap.api.maps.model.LatLng(22.531650, 114.224823));
        var0.add(new com.amap.api.maps.model.LatLng(22.548767, 114.247829));
        var0.add(new com.amap.api.maps.model.LatLng(22.555107, 114.278195));
        var0.add(new com.amap.api.maps.model.LatLng(22.568399, 114.312063));
        var0.add(new com.amap.api.maps.model.LatLng(22.589030, 114.322414));
        var0.add(new com.amap.api.maps.model.LatLng(22.581747, 114.422362));
        var0.add(new com.amap.api.maps.model.LatLng(22.541161, 114.468636));
        var0.add(new com.amap.api.maps.model.LatLng(22.512846, 114.472671));
        var0.add(new com.amap.api.maps.model.LatLng(22.462092, 114.476686));
        var0.add(new com.amap.api.maps.model.LatLng(22.419542, 114.494002));
        var0.add(new com.amap.api.maps.model.LatLng(22.363740, 114.464569));
        var0.add(new com.amap.api.maps.model.LatLng(22.254018, 114.425275));
        var0.add(new com.amap.api.maps.model.LatLng(22.173216, 114.374778));
        var0.add(new com.amap.api.maps.model.LatLng(22.132902, 114.350657));
        var0.add(new com.amap.api.maps.model.LatLng(22.117578, 114.248971));
        var0.add(new com.amap.api.maps.model.LatLng(22.115810, 114.128565));
        var0.add(new com.amap.api.maps.model.LatLng(22.155008, 113.999891));
        var0.add(new com.amap.api.maps.model.LatLng(22.198143, 113.940663));
        var0.add(new com.amap.api.maps.model.LatLng(22.197552, 113.884447));
        var0.add(new com.amap.api.maps.model.LatLng(22.192136, 113.829611));
        var0.add(new com.amap.api.maps.model.LatLng(22.220545, 113.807664));
        var0.add(new com.amap.api.maps.model.LatLng(22.249156, 113.787547));
        var0.add(new com.amap.api.maps.model.LatLng(22.319915, 113.841737));
        var0.add(new com.amap.api.maps.model.LatLng(22.361818, 113.873481));
        var0.add(new com.amap.api.maps.model.LatLng(22.445883, 113.929154));
        var0.add(new com.amap.api.maps.model.LatLng(22.445883, 113.929154));
        if (var0 != null && var0.size() != 0 && var1 != null) {
            int var2;
            for (var2 = 0; var2 < var0.size(); ++var2) {
                if (var1.longitude == ((com.amap.api.maps.model.LatLng) var0.get(var2)).longitude && var1.latitude == ((com.amap.api.maps.model.LatLng) var0.get(var2)).latitude) {
                    return true;
                }
            }
            var2 = 0;
            boolean var3 = false;
            com.amap.api.maps.model.LatLng var4 = null;
            com.amap.api.maps.model.LatLng var5 = null;
            double var6 = 0.0D;
            int var8 = var0.size();
            for (int var9 = 0; var9 < var8; ++var9) {
                var4 = (com.amap.api.maps.model.LatLng) var0.get(var9);
                var5 = (com.amap.api.maps.model.LatLng) var0.get((var9 + 1) % var8);
                if (var4.latitude != var5.latitude && var1.latitude >= Math.min(var4.latitude, var5.latitude) && var1.latitude <= Math.max(var4.latitude, var5.latitude)) {
                    var6 = (var1.latitude - var4.latitude) * (var5.longitude - var4.longitude) / (var5.latitude - var4.latitude) + var4.longitude;
                    if (var6 == var1.longitude) {
                        return true;
                    }
                    if (var6 < var1.longitude) {
                        ++var2;
                    }
                }
            }
            return var2 % 2 == 1;
        } else {
            return false;
        }
    }


    /**
     * 调换集合中两个指定位置的元素, 若两个元素位置中间还有其他元素，需要实现中间元素的前移或后移的操作。
     *
     * @param list        集合
     * @param oldPosition 需要调换的元素
     * @param newPosition 被调换的元素
     * @param <T>
     */
    public static <T> List swap2(List<T> list, int oldPosition, int newPosition) {
        if (null == list) {
            throw new IllegalStateException("The list can not be empty...");
        }

        // 向前移动，前面的元素需要向后移动
        if (oldPosition < newPosition) {
            for (int i = oldPosition; i < newPosition; i++) {
                Collections.swap(list, i, i + 1);
            }
        }
        // 向后移动，后面的元素需要向前移动
        if (oldPosition > newPosition) {
            for (int i = oldPosition; i > newPosition; i--) {
                Collections.swap(list, i, i - 1);
            }
        }
        return list;
    }

    private static Boolean isCreateChannel = false;
    private static NotificationManager notificationManager;

    public static Notification myNotification(Activity activity, NotificationData data) {
        Notification.Builder builder = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= 26) {
            if (null == notificationManager) {
                notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = activity.getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        data.getTitle(), NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(activity.getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(activity.getApplicationContext());
        }
        Intent intent = new Intent(activity, data.getType().equals("audit") ? NotificationlistActivity.class : ActivitiesActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
        builder.setSmallIcon(R.drawable.jstyle_icon)
                .setContentTitle(data.getTitle())
                .setContentText(data.getMsg())
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis());
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }


    /**
     * 对象转换成json字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        Gson gson = new Gson();
        return gson.toJson(obj);
    }


    /**
     * json字符串转成对象
     *
     * @param str
     * @param type
     * @return
     */
    public static <T> T fromJson(String str, Type type) {
        Gson gson = new Gson();
        return gson.fromJson(str, type);
    }

    /**
     * json字符串转成对象
     *
     * @param str
     * @param type
     * @return
     */
    public static <T> T fromJson(String str, Class<T> type) {
        Gson gson = new Gson();
        return gson.fromJson(str, type);
    }

    /**
     * 是否是俄语
     *
     * @param context
     * @return
     */
    public static boolean IsRussian(Context context) {
        return context.getResources().getConfiguration().locale.toString().toLowerCase().contains("ru");
    }


    /**
     * 获取ISO_3166_1
     *
     * @param context
     * @return
     */
    public static String GetISO_3166_1(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        return null == locale.getCountry() ? "CN" : locale.getCountry().toUpperCase().trim();
    }

    public static BindDeviceInfo showBindDeviceList() {
        List<BindDeviceInfo> bindDeviceInfoList = BindDeviceInfoDaoManager.queryAllData();
        String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        if (!TextUtils.isEmpty(address)) {
            BindDeviceInfo firstBind = null;
            for (BindDeviceInfo bindDeviceInfo : bindDeviceInfoList) {
                if (address.equals(bindDeviceInfo.getMacAddress())) {
                    firstBind = bindDeviceInfo;
                }
            }
            if (firstBind != null) {
                bindDeviceInfoList.remove(firstBind);
                bindDeviceInfoList.add(0, firstBind);
            }
        }
        return bindDeviceInfoList.size() == 0 ? null : bindDeviceInfoList.get(0);
    }

    //判断是否运动了二十分钟
    public static boolean is20minte(PathRecord pathRecord) {
        if ("0".equals(pathRecord.getMDuration()) || null == pathRecord) {
            return false;
        } else {
            return (Long.valueOf(pathRecord.getMDuration()) / 60) >= 20;
        }
    }


    /**
     * 压缩文件和文件夹
     *
     * @param srcFileString 要压缩的文件或文件夹
     * @param zipFileString 压缩完成的Zip路径
     * @throws Exception
     */
    public static void ZipFolder(String srcFileString, String zipFileString) throws Exception {
        //创建ZIP
        ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
        //创建文件
        File file = new File(srcFileString);
        //压缩
        ZipFiles(file.getParent() + File.separator, file.getName(), outZip);
        //完成和关闭
        outZip.finish();
        outZip.close();
    }


    /**
     * 压缩文件
     *
     * @param folderString
     * @param fileString
     * @param zipOutputSteam
     * @throws Exception
     */
    private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
        if (zipOutputSteam == null)
            return;
        File file = new File(folderString + fileString);
        if (file.isFile()) {
            ZipEntry zipEntry = new ZipEntry(fileString);
            FileInputStream inputStream = new FileInputStream(file);
            zipOutputSteam.putNextEntry(zipEntry);
            int len;
            byte[] buffer = new byte[4096];
            while ((len = inputStream.read(buffer)) != -1) {
                zipOutputSteam.write(buffer, 0, len);
            }
            zipOutputSteam.closeEntry();
        }
    }


    /**
     * 当前activity的名字 Service中无法使用
     *
     * @param context
     * @return
     */
    public static String getRunningActivityName(Context context) {
        String contextString = context.toString();
        return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
    }


    public static void GoAppShop(String pakegename, Context context) {
        if (TextUtils.isEmpty(pakegename) || null == context) {
            return;
        }
        if("com.facebook.katana".equals(pakegename)||"com.twitter.android".equals(pakegename)||"com.google.android.apps.plus".equals(pakegename)){
            try{
                Uri uri = Uri.parse("http://play.google.com/store/apps/details?id="+pakegename);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }catch (Exception e){ e.printStackTrace(); }
        }else{
            try {
                Uri uri = Uri.parse("market://details?id=" + pakegename);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) { e.printStackTrace(); }//您没有安装应用市场
        }


    }

    public static boolean isRightPsdFormat(String psd){
        String r = "[0-9A-Za-z_]*";
        return psd.matches(r);
    }
    public static void setEditTextInhibitInputSpace(EditText editText){
        InputFilter filter=new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if(source.equals(" "))return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }





}
